<template>
  <view class="countdown" :style="customStyle">
    <text class="countdown-text" v-if="!$slots.default">{{ timeText }}</text>
    <slot v-else v-bind:slotTime="current" />
  </view>
</template>

<script>
import { computed, watch } from 'vue'
import { useCountDown } from './use'
import { parseFormat } from './utils'
import { useExpose } from './use-expose'

export default {
  name: 'CountDown',
  props: {
    // 倒计时时长，单位毫秒
    time: {
      type: Number,
      default: 0
    },

    // 时间格式, DD-日, HH-时, mm-分, ss-秒
    format: {
      type: String,
      default: 'HH:mm:ss'
    },

    // 自定义样式
    customStyle: {
      type: String,
      default: ''
    },

    millisecond: Boolean,

    autoStart: {
      type: Boolean,
      default: true
    }
  },
  emits: ['change', 'finish'],
  setup (props, { emit }) {
    const { start, pause, reset, current } = useCountDown({
      time: +props.time,
      millisecond: props.millisecond,
      onChange: (current) => emit('change', current),
      onFinish: () => emit('finish')
    })

    const timeText = computed(() => parseFormat(props.format, current.value))

    const resetTime = () => {
      reset(+props.time)

      if (props.autoStart) {
        start()
      }
    }

    watch(() => props.time, resetTime, { immediate: true })

    useExpose({
      start,
      pause,
      reset: resetTime
    })

    return {
      resetTime,
      timeText,
      current
    }
  }
}
</script>

<style></style>
